package evostar.rabbitmq;

import evostar.VO.GoodsVO;
import evostar.model.OrderInfo;
import evostar.model.User;
import evostar.service.GoodsService;
import evostar.service.OrderService;
import evostar.service.RedisService;
import evostar.service.SeckillService;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class MQReceiver {
    @Autowired
    private RedisService redisService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private SeckillService seckillService;


    @RabbitListener(queues = MQConfig.SECKILL_QUEUE)
    public void seckillReceive(String msg) {
        SeckillMessage message = redisService.stringToBean(msg, SeckillMessage.class);
        User user = message.getUser();
        int goodsId = message.getGoodsId();


        GoodsVO goods = goodsService.getGoodsByGoodsId(goodsId);
        if (goods.getSeckillStock() <= 0) {
            return;
        }

        OrderInfo order = orderService.getSeckillOrderByUserIdGoodsId(user.getId(), goodsId);
        if (order != null) {
            return;
        }
        seckillService.seckill(user, goods);
    }
}
